package auth

import (
	"net/http"
	"time"

	"kubem/config"
	"kubem/middleware"
	"kubem/models"
	"kubem/pkg/logger"
	"kubem/pkg/response"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
)

func Login(c *gin.Context) {
	var user models.User
	if err := c.ShouldBindJSON(&user); err != nil {
		logger.Error("Error binding JSON in login request:", err)
		c.JSON(http.StatusBadRequest, response.Response{Code: 400, Message: "invalid request"})
		return
	}
	logger.Infof("User [%s] login", user.Username)

	// 这里应该从数据库等地方验证用户名和密码，此处直接加载配置文件的用户密码
	if user.Username == config.Conf.Auth.Username && user.Password == config.Conf.Auth.Password {
		expireAt := config.Conf.Jwt.Expire
		// 生成JWT token
		claims := middleware.CustomClaims{
			Username: user.Username,
			RegisteredClaims: jwt.RegisteredClaims{
				ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expireAt) * time.Second)),
				IssuedAt:  jwt.NewNumericDate(time.Now()),
				Issuer:    "kubem",
			},
		}
		token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
		signedToken, _ := token.SignedString([]byte(config.Conf.Jwt.Secret))
		logger.Infof("[%s] login successful", user.Username)
		c.JSON(http.StatusOK, response.Response{Code: 200, Message: "login successful", Data: map[string]interface{}{"token": signedToken}})
	} else {
		logger.Info("Invalid credentials for user:", user.Username)
		c.JSON(http.StatusUnauthorized, response.Response{Code: 401, Message: "invalid credentials"})
	}
}

// Logout 处理用户注销请求
func Logout(c *gin.Context) {
	// 可以在这里添加更复杂的逻辑，比如将该用户对应的token记录为失效状态（结合数据库、缓存等）
	// 目前简单返回成功提示，让客户端清除本地存储的token
	logger.Info("User logout request received")
	c.JSON(http.StatusOK, response.Response{Code: 200, Message: "Logout successful, please clear your local token"})

}
